package com.boot2551.common;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Filter为接口
 * 表示admin下的所有资源先进入过滤器，再进入控制层
 */
@WebFilter(value = "/admin/*")
public class LoginFilterAdmin implements Filter {
    /**
     *
     * @param filterConfig 过滤配置接口
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化filter");
    }

    /**
     *
     * @param servletRequest  请求接口
     * @param servletResponse 响应父接口
     * @param filterChain 过滤链接口
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("执行过滤");
//        页面->过滤器->控制层
        //从服务器中获取管理员数据，如果有则放行资源，没有则进入登录页面
        HttpServletRequest req=(HttpServletRequest)servletRequest;
        //session接口：它可实现同一浏览器数据共享,数据保存在服务端,通过键值对保存数据(数据为任意的object对象),默认时间30分钟有效，客户端保存的是它对应的sessionid
        HttpSession session=req.getSession();
        //取session
        Object r=session.getAttribute("ad");
        if (r!=null){
            filterChain.doFilter(servletRequest,servletResponse);

        }else{
            //响应子接口
            HttpServletResponse resp=(HttpServletResponse)servletResponse;
            //req.getContextPath()表示项目路径
            resp.sendRedirect(req.getContextPath()+"/login.html");
        }
    }

    @Override
    public void destroy() {
        System.out.println("销毁filter");
    }
}
